<template>
  <view class="form-container">
    <!-- 1. 顶部导航栏（优化定位与视觉） -->
    <view>
      <view
        style="position: absolute; top: 110rpx; left: 30rpx"
        @click="goBack"
      >
        <u-icon name="arrow-left" color="white" size="30"></u-icon>
      </view>
      <view class="header">
        <text class="header-title">发布招聘需求</text>
      </view>
    </view>
    <!-- 2. 头部说明区（新增渐变背景+卡片感） -->
    <view class="header-card">
      <text class="header-subtitle"
        >请完善以下信息，我们将为您精准匹配合适人才</text
      >
    </view>

    <view class="form-wrapper">
      <u--form
        :model="form"
        ref="dataForm"
        :rules="rules"
        labelPosition="left"
        labelWidth="0"
        :labelStyle="{ color: '#333', fontWeight: '500', fontSize: '28rpx' }"
        class="form-inner"
      >
        <u-form-item prop="company_name" :borderBottom="false">
          <view class="form-section">
            <view class="section-label">
              <text class="label-text">用人单位</text>
              <text class="required-mark">*</text>
            </view>
            <u--input
              v-model="form.company_name"
              placeholder="请填写用人单位"
              class="form-input"
            />
          </view>
        </u-form-item>
        <u-form-item prop="job_type" :borderBottom="false">
          <view class="form-section">
            <view class="section-label">
              <text class="label-text">招聘类型</text>
              <text class="required-mark">*</text>
            </view>
            <u-radio-group v-model="form.job_type" class="radio-group">
              <u-radio
                v-for="item in jobTypeOptions"
                :key="item.value"
                :label="item.label"
                :name="item.value"
                shape="circle"
                activeColor="#4A90E2"
                inactiveColor="#eee"
                class="radio-item"
                :iconSize="24"
                :labelStyle="{
                  marginLeft: '15px',
                }"
              />
            </u-radio-group>
          </view>
        </u-form-item>
        <u-form-item prop="title" :borderBottom="false">
          <view class="form-section">
            <view class="section-label">
              <text class="label-text">招聘标题</text>
              <text class="required-mark">*</text>
            </view>
            <u--input
              v-model="form.title"
              placeholder="请填写职位名称，如“铁塔生产主管”"
              class="form-input"
              placeholder-class="input-placeholder"
              @focus="handleInputFocus($event, 'title')"
              @blur="handleInputBlur('title')"
              :class="{ 'input-focused': focusedInput == 'title' }"
            />
            <text class="hint-text" v-if="focusedInput == 'title'">
              建议包含岗位名称+核心要求，提升曝光率
            </text>
          </view>
        </u-form-item>
        <u-form-item prop="city_address" :borderBottom="false">
          <view class="form-section">
            <view class="section-label">
              <text class="label-text">工作地点</text>
              <text class="required-mark">*</text>
            </view>
            <u--input
              v-model="form.city_address"
              placeholder="请输入工作地点"
              placeholderStyle="color: #999;"
              :customStyle="{ fontSize: '28rpx' }"
            />
          </view>
        </u-form-item>
        <u-form-item prop="history_need" :borderBottom="false">
          <view class="form-section">
            <view class="section-label">
              <text class="label-text">经验要求</text>
              <text class="required-mark">*</text>
            </view>
            <u--input
              v-model="form.history_need"
              placeholder="请输入经验要求"
              placeholderStyle="color: #999;"
              :customStyle="{ fontSize: '28rpx' }"
            />
          </view>
        </u-form-item>
        <u-form-item prop="xue_li_need" :borderBottom="false">
          <view class="form-section">
            <view class="section-label">
              <text class="label-text">最低学历</text>
              <text class="required-mark">*</text>
            </view>
            <u--input
              v-model="form.xue_li_need"
              placeholder="请输入最低学历"
              placeholderStyle="color: #999;"
              :customStyle="{ fontSize: '28rpx' }"
            />
          </view>
        </u-form-item>
        <u-form-item prop="salary" :borderBottom="false">
          <view class="form-section">
            <view class="section-label">
              <text class="label-text">薪资范围</text>
              <text class="required-mark">*</text>
            </view>
            <u--input
              v-model="form.salary"
              placeholder="请输入薪资范围"
              placeholderStyle="color: #999;"
              :customStyle="{ fontSize: '28rpx' }"
            />
          </view>
        </u-form-item>

        <view class="form-section">
          <view class="section-label">
            <text class="label-text">本信息截止有效期</text>
            <text class="required-mark">*</text>
          </view>
          <view
            @click="state.validPickerShow = true"
            style="
              border: 1px solid #e4e7ed;
              padding: 10px;
              border-radius: 5px;
              color: #606266;
            "
          >
            {{ form.show_end_date ? form.show_end_date : "选择信息截止日期" }}
          </view>
          <u-datetime-picker
            :show="state.validPickerShow"
            v-model="form.show_end_date"
            :formatter="formatter"
            mode="date"
            @confirm="validPickerConfirm"
            @cancel="state.validPickerShow = false"
          ></u-datetime-picker>
        </view>
        <view class="form-section">
          <view class="section-label">
            <text class="label-text">职位描述</text>
            <text class="required-mark">*</text>
          </view>
          <view class="editor-container">
            <sp-editor
              v-model="form.content"
              :editorId="`editor-${state.id || 'new'}`"
              :toolbar-config="{
                excludeKeys: [
                  'direction',
                  'date',
                  'lineHeight',
                  'letterSpacing',
                  'listCheck',
                ],
                iconSize: '22rpx',
                keys: [
                  'bold',
                  'italic',
                  'underline',
                  'align',
                  'fontSize',
                  'color',
                  'link',
                  'listOrdered',
                  'listBullet',
                  'divider',
                  'undo',
                  'redo',
                  'removeFormat',
                ],
              }"
              placeholder="介绍工作内容、职位要求、特别说明"
              @init="initEditor"
              @input="inputOver"
              @upinImage="handleUploadImage"
              @overMax="handleOverMax"
              maxlength="2000"
              class="editor-inner"
            ></sp-editor>
          </view>
          <view class="editor-footer">
            <text class="hint-text">介绍工作内容、职位要求、特别说明</text>
          </view>
        </view>
      </u--form>

      <!-- 3.5 提交按钮（优化渐变+hover效果+加载状态） -->
      <view class="submit-section">
        <u-button
          type="primary"
          :text="
            isSubmitting ? '提交中...' : state.id ? '修改需求' : '提交需求'
          "
          @click="submitForm"
          shape="circle"
          size="large"
          :customStyle="{
            width: '100%',
            height: '90rpx',
            borderRadius: '45rpx',
            fontSize: '32rpx',
            fontWeight: '500',
            background: 'linear-gradient(135deg, #4A90E2 0%, #357ABD 100%)',
            border: 'none',
            marginTop: '20rpx',
            boxShadow: '0 8rpx 24rpx rgba(74, 144, 226, 0.3)',
            transition: 'all 0.3s ease',
          }"
          :loading="isSubmitting"
          loadingColor="#fff"
          class="submit-btn"
        />
        <text class="tip-text"
          >提交后我们将在1-2个工作日内审核，审核通过后将展示</text
        >
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, toRefs, onUnmounted, computed } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { GetSysLabel, PostZhaoPinSave, GetZhaoPinRead } from "@/api/news.js";
import { showToast, showLoading, hideLoading } from "@/utils/toast";
import { formatDate } from "@/utils/date.js";
// 1. 状态管理：新增输入框聚焦状态、表单验证状态
const state = reactive({
  id: null, // 编辑时的需求ID（新增时为null）
  SysLabelList: [], // 关键词列表
  editorIns: null, // 富文本编辑器实例
  isSubmitting: false, // 防止重复提交
  focusedInput: "", // 当前聚焦的输入框（用于显示提示/样式变化）
  validPickerShow: false,
  // 招聘类型选项（保持原有）
  jobTypeOptions: [
    { label: "全职", value: 1 },
    { label: "兼职", value: 2 },
  ],
  form: {
    company_name: "", // 用人单位
    job_type: "", // 招聘类型：1=全职，2=兼职
    title: "", // 职位名称
    content: "", // 职位描述
    city_address: "", // 工作地点
    history_need: "", // 经验要求
    xue_li_need: "", // 最低学历
    salary: "", // 薪资范围
    show_end_date: "", // 截止日期
  },
  rules: {
    company_name: [
      { required: true, message: "请输入用人单位", trigger: "blur" },
    ],
    title: [{ required: true, message: "请输入职位名称", trigger: "blur" }],
    city_address: [
      { required: true, message: "请输入公司名称", trigger: "blur" },
    ],
    history_need: [
      { required: true, message: "请输入公司名称", trigger: "blur" },
    ],
    xue_li_need: [
      { required: true, message: "请输入最低学历", trigger: "blur" },
    ],
    salary: [{ required: true, message: "请输入薪资范围", trigger: "blur" }],
  },
});

// 解构响应式变量
const { isSubmitting, jobTypeOptions, focusedInput, form, rules } =
  toRefs(state);
const dataForm = ref(null); // u-form表单实例

// 3. 页面加载：初始化关键词列表 + 编辑场景回显（优化加载体验）
onLoad(async (e) => {
  showLoading("加载中...");
  try {
    // 编辑场景：接收ID并回显数据
    if (e.id) {
      state.id = e.id;
      await init(); // 加载历史需求数据
    }
  } catch (error) {
    showToast("页面加载失败，请重试");
  } finally {
    hideLoading();
  }
});

// 5. 编辑场景：加载历史需求数据（优化回显逻辑）
const init = async () => {
  try {
    const res = await GetZhaoPinRead({ id: state.id });
    if (res.code !== 10000) throw new Error(res.msg);
  } catch (error) {
    showToast(error.message || "历史数据加载失败");
    goBack(); // 加载失败返回上一页
  }
};

// 6. 富文本编辑器核心逻辑（新增字数统计）
const initEditor = (editor, id) => {
  state.editorIns = editor;
  console.log(editor);

  // 编辑场景回显（补充判断）
  if (state.id && form.value.content) {
    editor.setContents({ html: form.value.content });
  }
};
const inputOver = (e) => {
  // console.log(e.html);
  form.value.content = e.html;
};
// 7. 输入框交互（新增聚焦/失焦效果）
const handleInputFocus = (e, inputName) => {
  state.focusedInput = inputName;
};
const handleInputBlur = (inputName) => {
  // 延迟失焦，让用户看到提示
  setTimeout(() => {
    if (state.focusedInput === inputName) {
      state.focusedInput = "";
    }
  }, 1000);
};

// 8. 表单提交（优化验证逻辑+重复提交防护）
const submitForm = async () => {
  dataForm.value.validate().then(async (valid) => {
    if (valid) {
      // // 2. 防止重复提交
      if (state.isSubmitting) return;
      state.isSubmitting = true;

      try {
        showLoading(state.id ? "修改中..." : "提交中...");
        // 提交数据（区分新增/编辑）
        const res = await PostZhaoPinSave({
          ...form.value,
          id: state.id, // 编辑时携带ID
        });

        if (res.code == 10000) {
          showToast(state.id ? "修改成功" : "招聘已发送，审核通过后方可查看");
          // 延迟返回，确保用户看到提示
          setTimeout(() => {
            goBack();
          }, 1500);
        } else {
          showToast(res.message || "操作失败，请重试");
        }
      } catch (error) {
        showToast("网络错误，请重试");
        console.error("提交需求错误:", error);
      } finally {
        state.isSubmitting = false;
        hideLoading();
      }
    } else {
      showToast("请检查表单是否填写完整");
    }
  });
};

// 9. 辅助方法（保持原有）
const goBack = () => {
  uni.navigateBack({ delta: 1 });
};

// 页面卸载：销毁编辑器实例（防止内存泄漏）
onUnmounted(() => {
  state.editorIns = null;
});

// 图片上传方法（原有逻辑，若需实现可补充）
const handleUploadImage = async (params) => {
  // 示例：调用图片上传接口，返回图片URL
  // try {
  //   const res = await uploadImage(params.file);
  //   params.success(res.data.url); // 通知编辑器图片上传成功
  // } catch (error) {
  //   params.fail(); // 通知编辑器图片上传失败
  // }
  showToast("图片上传功能待实现");
  params.fail();
};
// 信息有效期选择器确认
const validPickerConfirm = (e) => {
  form.value.show_end_date = formatDate(new Date(e.value), "YYYY-MM-DD");
  state.validPickerShow = false;
};
const formatter = (type, value) => {
  if (type === "year") {
    return `${value}年`;
  }
  if (type === "month") {
    return `${value}月`;
  }
  if (type === "day") {
    return `${value}日`;
  }
  return value;
};
</script>

<style lang="scss" scoped>
:deep(.u-form-item__body) {
  padding: 0 !important;
}
.form-container {
  min-height: 100vh;
  background: linear-gradient(180deg, #f8f9fa 0%, #ffffff 100%);
  padding-bottom: 40rpx;
  .header {
    background: linear-gradient(135deg, #4a90e2 0%, #357abd 100%);
    padding: 100rpx 40rpx 40rpx;
    text-align: center;
    color: white;

    .header-title {
      display: block;
      font-size: 40rpx;
      font-weight: bold;
      margin-bottom: 16rpx;
    }

    .header-subtitle {
      font-size: 26rpx;
      opacity: 0.9;
      line-height: 1.4;
    }
  }
}
/* 1. 顶部导航栏（优化定位） */
.top-nav {
  background: linear-gradient(135deg, #4a90e2 0%, #357abd 100%);
  padding: 40rpx 30rpx 20rpx;
  display: flex;
  align-items: center;
  position: relative;
  box-shadow: 0 4rpx 12rpx rgba(74, 144, 226, 0.2);

  .back-icon {
    cursor: pointer;
  }

  .nav-title {
    font-size: 34rpx;
    font-weight: 600;
    color: white;
    margin-left: 24rpx;
  }
}

/* 2. 头部说明卡片（新增） */
.header-card {
  background-color: white;
  margin: 10px 30rpx -20rpx;
  padding: 30rpx;
  border-radius: 24rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.06);
  position: relative;
  z-index: 1;

  .header-subtitle {
    font-size: 26rpx;
    color: #666;
    line-height: 1.6;
    text-align: center;
  }
}

/* 3. 表单容器（增强卡片感） */
.form-wrapper {
  margin: 40rpx 30rpx 20rpx;
  background: white;
  border-radius: 24rpx;
  padding: 40rpx 30rpx;
  box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.08);
  position: relative;
  z-index: 2;
}

.form-inner {
  width: 100%;
}

/* 4. 表单 section 通用样式 */
.form-section {
  margin-bottom: 50rpx;
  width: 100%;
  position: relative;

  &:last-child {
    margin-bottom: 10rpx;
  }

  // 标签样式（带必填星号）
  .section-label {
    display: flex;
    align-items: center;
    margin-bottom: 16rpx;

    .label-text {
      font-size: 28rpx;
      font-weight: 500;
      color: #333;
    }

    .required-mark {
      color: #ff4d4f;
      margin-left: 8rpx;
      font-size: 28rpx;
    }
  }

  // 提示文本样式
  .hint-text {
    display: block;
    margin-top: 12rpx;
    font-size: 24rpx;
    color: #666;
    line-height: 1.5;
    padding-left: 4rpx;
    animation: fadeIn 0.3s ease;
  }
}

/* 5. 输入框样式（带聚焦动画） */
.form-input {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  padding: 0 20rpx;
  background-color: #f9f9f9;
  border-radius: 16rpx;
  font-size: 28rpx;
  transition: all 0.3s ease;

  &.input-focused {
    background-color: #fff;
    border: 2rpx solid #4a90e2;
    box-shadow: 0 0 0 8rpx rgba(74, 144, 226, 0.1);
  }
}

.input-placeholder {
  color: #999;
  font-size: 26rpx;
}

/* 6. 复选框样式优化 */
.checkbox-grid {
  width: 100%;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16rpx 20rpx;
}

.checkbox-item {
  padding: 16rpx 20rpx;
  background-color: #f9f9f9;
  border-radius: 12rpx;
  transition: all 0.2s ease;

  &:active {
    background-color: #f0f5ff;
  }
}

:deep(.u-checkbox__icon--checked) {
  background-color: #4a90e2 !important;
  border-color: #4a90e2 !important;
}

:deep(.u-checkbox__icon) {
  transition: all 0.2s ease;
}

/* 7. 单选框样式优化 */
.radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  padding: 10rpx 0;
}

.radio-item {
  padding: 16rpx 30rpx;
  background-color: #f9f9f9;
  border-radius: 12rpx;
  transition: all 0.2s ease;

  &:active {
    background-color: #f0f5ff;
  }
}

:deep(.u-radio__icon--checked) {
  background-color: #4a90e2 !important;
  border-color: #4a90e2 !important;
}

/* 8. 富文本编辑器样式 */
.editor-container {
  border: 2rpx solid #f0f0f0;
  border-radius: 16rpx;
  overflow: hidden;
  transition: border-color 0.3s ease;

  &:focus-within {
    border-color: #4a90e2;
  }
}

.editor-inner {
  min-height: 300rpx;
  padding: 20rpx;
}

.editor-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 16rpx;
  padding: 0 4rpx;
}

.word-count {
  font-size: 24rpx;
  color: #999;
}

/* 9. 提交按钮样式 */
.submit-section {
  margin-top: 60rpx;
  text-align: center;
}

:deep(.submit-btn) {
  &:hover {
    transform: translateY(-2rpx);
    box-shadow: 0 12rpx 30rpx rgba(74, 144, 226, 0.4);
  }

  &:active {
    transform: translateY(0);
    box-shadow: 0 6rpx 18rpx rgba(74, 144, 226, 0.3);
  }

  &:disabled {
    opacity: 0.7;
    cursor: not-allowed;
    transform: none;
    box-shadow: none;
  }
}

.tip-text {
  display: block;
  color: #999;
  font-size: 24rpx;
  margin-top: 20rpx;
  line-height: 1.5;
  padding: 0 10rpx;
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 适配深色模式（可选） */
@media (prefers-color-scheme: dark) {
  .form-container {
    background-color: #1a1a1a;
  }

  .header-card,
  .form-wrapper {
    background-color: #2c2c2c;
  }

  .label-text,
  .nav-title,
  .username {
    color: #f5f5f5;
  }

  .header-subtitle,
  .hint-text,
  .tip-text,
  .word-count {
    color: #b0b0b0;
  }

  .form-input,
  .checkbox-item,
  .radio-item {
    background-color: #3a3a3a;
    color: #f5f5f5;
  }

  .input-placeholder {
    color: #888;
  }
}
</style>
